type Response = {
  url: string;
  body: any,
  status: number;
  type: string,
  statusText?: string;
  _data?: any;
  headers?: object,
  ok?: boolean,
  redirected?: boolean,
  bodyUsed?: boolean,
};
type ResponseData = {
  code: number,
  msg: string,
  data: object | object[]
}

import { useTimestamp } from '@vueuse/core'
export const useRequest = async (url: string, options: object) => {
  const router = useRouter();
  const store = useMainStore();
  const appConfig = useAppConfig();
  const host = window.location.hostname;
  const headers = {
    // Authorization:'Bearer '+store.user?.token,
    // tokenID: store.user?.tokenID || null
  };
  const config = {
    server: true
  };
  const defaultOptions: object = {
    baseURL: appConfig.app.apiUrl,
    headers: headers,
    onResponse({ response }: { response: Response }) {
      const res = response._data;
      if (res.error === 401) {
        router.replace("/login");
        store.logout()
      }
      else if (res.error !== 0) {
      } else {
        //登录成功操作
      }
    },
    onResponseError({ response }: { response: Response }) {
      console.log("response-error", response);
      const res = response._data;
      if (response.status == 401) {
        router.replace("/login");
        store.logout()
      }
    },
  };
  const newOptions: object = { ...defaultOptions, ...options, timeout: 20000 };
  //防止重复请求
  let key = url + JSON.stringify(options);
  return new Promise((resolve, reject) => {
    useAsyncData(key, () => $fetch(url, newOptions), config).then(({ data, error }) => {
      // useFetch(url, { ...newOptions }).then(({ data, error }) => {
      if (error.value) {
        reject(error.value)
        return
      }
      resolve(data)
    }).catch((err: any) => {
      reject(err)
    })
  })
};
